package com.autoglm.android.core.execution

import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.PixelFormat
import android.hardware.display.DisplayManager
import android.hardware.display.VirtualDisplay
import android.media.Image
import android.media.ImageReader
import android.media.projection.MediaProjection
import android.media.projection.MediaProjectionManager
import android.os.Environment
import android.os.Handler
import android.os.Looper
import android.util.DisplayMetrics
import android.util.Log
import android.view.WindowManager
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

/**
 * 截图管理器，负责捕获屏幕截图和保存图片
 */
class ScreenshotManager(
    private val context: Context,
    private val mediaProjection: MediaProjection
) {
    companion object {
        private const val TAG = "ScreenshotManager"
        private const val VIRTUAL_DISPLAY_NAME = "AutoGLM-Screenshot"
    }
    
    private val metrics = DisplayMetrics()
    private val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
    private val mainHandler = Handler(Looper.getMainLooper())
    
    private var imageReader: ImageReader? = null
    private var virtualDisplay: VirtualDisplay? = null
    
    init {
        windowManager.defaultDisplay.getMetrics(metrics)
    }
    
    /**
     * 初始化虚拟屏幕
     */
    private fun initVirtualDisplay(width: Int, height: Int, dpi: Int) {
        imageReader = ImageReader.newInstance(width, height, PixelFormat.RGBA_8888, 2)
        
        virtualDisplay = mediaProjection.createVirtualDisplay(
            VIRTUAL_DISPLAY_NAME,
            width,
            height,
            dpi,
            DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
            imageReader?.surface,
            null,
            mainHandler
        )
    }
    
    /**
     * 释放资源
     */
    fun release() {
        virtualDisplay?.release()
        virtualDisplay = null
        
        imageReader?.close()
        imageReader = null
    }
    
    /**
     * 捕获屏幕截图
     * 
     * @return 屏幕截图的Bitmap
     */
    suspend fun captureScreenshot(): Bitmap? = withContext(Dispatchers.IO) {
        try {
            // 确保虚拟显示已初始化
            if (virtualDisplay == null) {
                initVirtualDisplay(
                    metrics.widthPixels,
                    metrics.heightPixels,
                    metrics.densityDpi
                )
            }
            
            val image = imageReader?.acquireLatestImage()
            if (image == null) {
                Log.e(TAG, "Failed to acquire screenshot image")
                return@withContext null
            }
            
            val bitmap = imageToBitmap(image)
            image.close()
            
            return@withContext bitmap
        } catch (e: Exception) {
            Log.e(TAG, "Error capturing screenshot", e)
            return@withContext null
        }
    }
    
    /**
     * 捕获并保存屏幕截图
     * 
     * @param filename 可选的文件名
     * @return 保存的文件路径，如果失败返回null
     */
    suspend fun captureAndSaveScreenshot(filename: String? = null): String? = withContext(Dispatchers.IO) {
        val bitmap = captureScreenshot() ?: return@withContext null
        
        val actualFilename = filename ?: generateScreenshotFilename()
        val file = saveImageToFile(bitmap, actualFilename)
        
        return@withContext file?.absolutePath
    }
    
    /**
     * 将Image转换为Bitmap
     */
    private fun imageToBitmap(image: Image): Bitmap {
        val width = image.width
        val height = image.height
        
        val planes = image.planes
        val buffer = planes[0].buffer
        val pixelStride = planes[0].pixelStride
        val rowStride = planes[0].rowStride
        val rowPadding = rowStride - pixelStride * width
        
        val bitmap = Bitmap.createBitmap(
            width + rowPadding / pixelStride,
            height,
            Bitmap.Config.ARGB_8888
        )
        bitmap.copyPixelsFromBuffer(buffer)
        
        // 裁剪到正确的尺寸
        return Bitmap.createBitmap(bitmap, 0, 0, width, height)
    }
    
    /**
     * 保存图像到文件
     */
    private fun saveImageToFile(bitmap: Bitmap, filename: String): File? {
        try {
            val picturesDir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES)
                ?: return null
                
            val screenshotsDir = File(picturesDir, "AutoGLM")
            if (!screenshotsDir.exists() && !screenshotsDir.mkdirs()) {
                Log.e(TAG, "Failed to create screenshots directory")
                return null
            }
            
            val file = File(screenshotsDir, filename)
            val outputStream = FileOutputStream(file)
            
            bitmap.compress(Bitmap.CompressFormat.JPEG, 90, outputStream)
            outputStream.flush()
            outputStream.close()
            
            Log.d(TAG, "Screenshot saved at ${file.absolutePath}")
            return file
        } catch (e: IOException) {
            Log.e(TAG, "Failed to save screenshot", e)
            return null
        }
    }
    
    /**
     * 生成截图文件名
     */
    private fun generateScreenshotFilename(): String {
        val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(Date())
        return "Screenshot_$timeStamp.jpg"
    }
    
    /**
     * 创建MediaProjection
     * 注意：需要先获取用户授权
     */
    class MediaProjectionProvider(private val context: Context) {
        companion object {
            private const val REQUEST_MEDIA_PROJECTION = 1001
        }
        
        private var mediaProjection: MediaProjection? = null
        
        /**
         * 请求屏幕捕获权限
         */
        fun requestMediaProjectionPermission(activity: android.app.Activity) {
            val projectionManager = context.getSystemService(Context.MEDIA_PROJECTION_SERVICE) as MediaProjectionManager
            activity.startActivityForResult(
                projectionManager.createScreenCaptureIntent(),
                REQUEST_MEDIA_PROJECTION
            )
        }
        
        /**
         * 处理权限请求结果
         */
        fun handlePermissionResult(resultCode: Int, data: Intent?): Boolean {
            if (resultCode != android.app.Activity.RESULT_OK || data == null) {
                Log.e(TAG, "Failed to get media projection permission")
                return false
            }
            
            val projectionManager = context.getSystemService(Context.MEDIA_PROJECTION_SERVICE) as MediaProjectionManager
            mediaProjection = projectionManager.getMediaProjection(resultCode, data)
            
            return mediaProjection != null
        }
        
        /**
         * 获取MediaProjection实例
         */
        fun getMediaProjection(): MediaProjection? = mediaProjection
        
        /**
         * 释放MediaProjection
         */
        fun release() {
            mediaProjection?.stop()
            mediaProjection = null
        }
    }
} 